<template>
	<div class="up-img">
		<el-upload class="avatar-uploader" action="https://upload.qiniup.com" :data="qn" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload">
			<img v-if="imgUrl" :src="imgUrl + '?imageView2/1/w/200/h/200'" class="avatar" />
			<i v-else class="el-icon-plus avatar-uploader-icon"></i>
		</el-upload>
	</div>
</template>

<script>
import { getToken } from '@/api/qiniu';
export default {
	props: {},
	data() {
		return {
			imgUrl: '',
			prefix:'property-backstage-management',//项目前缀
			qn: {
				token: '',
				key: ''
			}
		};
	},
	mounted() {
		this.getToken();
	},
	methods: {
		// 上传成功
		handleSuccess(res, file) {
			this.imgUrl = 'http://cdn.gexinit.com/' + res.key; // 这边显示图片，上传成功后会返回一个对象，包含一个hash和一个key,然后前边加上七牛云为你随机分配的域名就是图片的外链。查看这个域名可看下面的描述
			this.$emit('change',this.imgUrl);
		},
		// 上传之前判断
		beforeUpload(file) {
			this.qn.key = this.prefix +'/' + new Date().getTime() + file.name; // 通过设置key为文件名，上传到七牛中会显示对应的图片名
			const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
			const isLt10M = file.size / 1024 / 1024 < 1000;
			if (!isJPG) {
				error('上传头像图片只能是 JPG/PNG 格式!');
			}
			if (!isLt10M) {
				error('上传头像图片大小不能超过 1GB!');
			}
			return isJPG && isLt10M;
		},
		getToken() {
			this.qn.token = window.localStorage.getItem('QiniuToken');
			if (!this.qn.token) {
				getToken().then(res => {
					this.qn.token = res.uptoken;
					window.localStorage.setItem('QiniuToken', res.uptoken);
				});
			}
		}
	}
};
</script>

<style lang="scss">
.up-img {
	.dialogVideo {
		.el-dialog__body {
			padding: 20px;
		}
	}
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	.avatar-uploader .el-upload:hover {
		border-color: #409eff;
	}
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		line-height: 100px;
		text-align: center;
	}
	.avatar {
		width: 100px;
		height: 100px;
		display: block;
	}
}
</style>
